/* $Id: UsersServlet.java 130 2011-08-26 06:58:30Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import alt.djudge.frontend.server.datatypes.AbstractEntry;
import alt.djudge.frontend.server.datatypes.ContestUserEntry;
import alt.djudge.frontend.server.datatypes.UserEntry;
import alt.djudge.frontend.server.datatypes.custom.SchoolOlympUserDetailsEntry;
import alt.djudge.frontend.server.models.ContestUsersModel;
import alt.djudge.frontend.server.models.CoreInterface;
import alt.djudge.frontend.server.models.SessionsModel;
import alt.djudge.frontend.server.models.UserDetailsModel;
import alt.djudge.frontend.server.models.UsersModel;
import alt.djudge.frontend.server.utils.Linker;


public class UsersServlet extends AbstractDataServlet
{
	private static final long serialVersionUID = 1L;

	@Override
	protected CoreInterface<? extends AbstractEntry> getModel()
	{
		return UsersModel.getCore();
	}
	
	protected void processAction(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		/*if ("pass".equals(action))
		{
			UsersModel.generatePasswords(req.getParameter("prefix"));
		}
		else */
		if ("customEdit".equals(action))
		{
			UserEntry user = UsersModel.getUser(Long.parseLong(req.getParameter("id")));
			if (req.getParameter("changeLoginAllowed") != null)
			{
				boolean prevValue = user.getLoginAllowed();
				user.setLoginAllowed(!prevValue);
			}
			if (req.getParameter("changePassword") != null)
			{
				String password = req.getParameter("password");
				user.setPassword(password);
			}
			if (req.getParameter("killSessions") != null)
			{
				SessionsModel.deleteUserSessions(user.getId());
			}
			if (req.getParameter("changeFirstName") != null)
			{
				Map<String, Object> detailsFilter = new HashMap<String, Object>();
				detailsFilter.put("userId", user.getId());
				List<SchoolOlympUserDetailsEntry> listDetails = UserDetailsModel.getEntries(detailsFilter);
				SchoolOlympUserDetailsEntry userDetails2011 = listDetails.size() > 0 ? listDetails.get(0) : null;
				if (userDetails2011 != null)
				{
					userDetails2011.setFirstName(req.getParameter("firstName"));
					userDetails2011.makePersistent();
				}

			}
			if (req.getParameter("changeMiddleName") != null)
			{
				Map<String, Object> detailsFilter = new HashMap<String, Object>();
				detailsFilter.put("userId", user.getId());
				List<SchoolOlympUserDetailsEntry> listDetails = UserDetailsModel.getEntries(detailsFilter);
				SchoolOlympUserDetailsEntry userDetails2011 = listDetails.size() > 0 ? listDetails.get(0) : null;
				if (userDetails2011 != null)
				{
					userDetails2011.setMiddleName(req.getParameter("middleName"));
					userDetails2011.makePersistent();
				}

			}
			if (req.getParameter("changeLastName") != null)
			{
				Map<String, Object> detailsFilter = new HashMap<String, Object>();
				detailsFilter.put("userId", user.getId());
				List<SchoolOlympUserDetailsEntry> listDetails = UserDetailsModel.getEntries(detailsFilter);
				SchoolOlympUserDetailsEntry userDetails2011 = listDetails.size() > 0 ? listDetails.get(0) : null;
				if (userDetails2011 != null)
				{
					userDetails2011.setLastName(req.getParameter("lastName"));
					userDetails2011.makePersistent();
				}

			}
			if (req.getParameter("changeRegionName") != null)
			{
				Map<String, Object> detailsFilter = new HashMap<String, Object>();
				detailsFilter.put("userId", user.getId());
				List<SchoolOlympUserDetailsEntry> listDetails = UserDetailsModel.getEntries(detailsFilter);
				SchoolOlympUserDetailsEntry userDetails2011 = listDetails.size() > 0 ? listDetails.get(0) : null;
				if (userDetails2011 != null)
				{
					userDetails2011.setRegionName(req.getParameter("regionName"));
					userDetails2011.makePersistent();
				}

			}
			if (req.getParameter("changeSchoolName") != null)
			{
				Map<String, Object> detailsFilter = new HashMap<String, Object>();
				detailsFilter.put("userId", user.getId());
				List<SchoolOlympUserDetailsEntry> listDetails = UserDetailsModel.getEntries(detailsFilter);
				SchoolOlympUserDetailsEntry userDetails2011 = listDetails.size() > 0 ? listDetails.get(0) : null;
				if (userDetails2011 != null)
				{
					userDetails2011.setSchoolName(req.getParameter("schoolName"));
					userDetails2011.makePersistent();
				}

			}
			if (req.getParameter("changeTeacherName") != null)
			{
				Map<String, Object> detailsFilter = new HashMap<String, Object>();
				detailsFilter.put("userId", user.getId());
				List<SchoolOlympUserDetailsEntry> listDetails = UserDetailsModel.getEntries(detailsFilter);
				SchoolOlympUserDetailsEntry userDetails2011 = listDetails.size() > 0 ? listDetails.get(0) : null;
				if (userDetails2011 != null)
				{
					userDetails2011.setTeacherName(req.getParameter("teacherName"));
					userDetails2011.makePersistent();
				}

			}
			if (req.getParameter("changeFormNumber") != null)
			{
				Map<String, Object> detailsFilter = new HashMap<String, Object>();
				detailsFilter.put("userId", user.getId());
				List<SchoolOlympUserDetailsEntry> listDetails = UserDetailsModel.getEntries(detailsFilter);
				SchoolOlympUserDetailsEntry userDetails2011 = listDetails.size() > 0 ? listDetails.get(0) : null;
				if (userDetails2011 != null)
				{
					userDetails2011.setFormNumber(Integer.parseInt(req.getParameter("formNumber")));
					userDetails2011.makePersistent();
				}

			}
			//
			user.makePersistent();
		}
		else if ("editProfile".equals(action))
		{
			String username = req.getSession().getAttribute("username") != null ? req.getSession().getAttribute("username").toString() : "";
			String password = req.getSession().getAttribute("password") != null ? req.getSession().getAttribute("password").toString() : "";
			UserEntry user = UsersModel.getUser(username, password);
			
			if (user == null)
			{
				resp.sendRedirect(Linker.link("login.jsp?return=profile.jsp"));
				return;
			}
			
			System.out.println("Editing " + user);
			
			/*String name = req.getParameter("name");
			user.setName(name);
			String email = req.getParameter("email");
			user.setEmail(email);
			String region = req.getParameter("region");
			user.setRegion(region);
			String school = req.getParameter("school");
			user.setSchool(school);
			String group = req.getParameter("group");
			user.setGroup2(group);
			String timezone = req.getParameter("timezone");
			user.setTimezone(timezone);
			String usernameLviv = req.getParameter("usernameLviv");
			user.setUsernameLviv(usernameLviv);
			String usernameTopcoder = req.getParameter("usernameTopcoder");
			user.setUsernameTopcoder(usernameTopcoder);
			user.updateTopcoderColor();
			String usernameTimus = req.getParameter("usernameTimus");
			user.setUsernameTimus(usernameTimus);*/
			user.makePersistent();
			resp.sendRedirect(Linker.link("profile.jsp"));
		}
		else if ("editContestProfile".equals(action))
		{
			String username = req.getSession().getAttribute("username") != null ? req.getSession().getAttribute("username").toString() : "";
			String password = req.getSession().getAttribute("password") != null ? req.getSession().getAttribute("password").toString() : "";
			UserEntry user = UsersModel.getUser(username, password);
			if (user == null)
			{
				resp.sendRedirect(Linker.link("login.jsp?return=profile.jsp"));
				return;
			}
			
			String contestId = req.getParameter("contestId");
			ContestUserEntry contestUser = ContestUsersModel.getOrCreateEntry(Long.parseLong(contestId), user.getId());
			
			
			String name = req.getParameter("name");
			contestUser.setName(name);
			contestUser.makePersistent();
			
			String oldPass = req.getParameter("oldPassword");
			String newPass = req.getParameter("newPassword");
			if (password.equals(oldPass))
			{
				req.setAttribute("password", newPass);
				user.setPassword(newPass);
				user.makePersistent();
			}
			
			resp.sendRedirect(Linker.link("contests/home.jsp?contest_id=" + contestId));
		}
	}

	@Override
	protected boolean processEdit(HttpServletRequest req,
			HttpServletResponse resp)
	{
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String role = req.getParameter("role");
		String name = req.getParameter("name");
		String school = req.getParameter("school");
		String region = req.getParameter("region");
		String group = req.getParameter("group");
		HashMap<String, Object> map = new HashMap<String, Object>();
		try
		{
			Long idLong = id;
			map.put("id", idLong);
		}
		catch (Exception e) { }
		map.put("username", username);
		map.put("password", password);
		map.put("role", role);
		map.put("school", school);
		map.put("region", region);
		map.put("group", group);
		map.put("name", name);
		map.put("active", true);
		//id = UsersModel.editEntry(map);
		return true;
	}
}
